<template>
  <div v-loading="loading" class="risk-assessment">
    <!-- AI 风险评估生成部分 -->
    <div v-if="aiRiskList.length > 0" class="risk-section">
      <h3 class="section-title">
        {{ t("healthRecords.riskAssessment.sections.aiGenerated") }}
      </h3>

      <div
        v-for="aiRisk in aiRiskList"
        :key="aiRisk.riskAssessmentId"
        class="risk-item"
      >
        <div class="risk-header">
          <span class="risk-label">{{ aiRisk.title }}</span>
          <el-link type="primary" @click="quoteAiRisk(aiRisk)">{{
            t("healthRecords.riskAssessment.buttons.quote")
          }}</el-link>
        </div>
        <p class="risk-content">{{ aiRisk.content }}</p>
      </div>
    </div>

    <!-- 医生自定义风险评估 -->
    <div class="risk-section">
      <h3 class="section-title">
        {{ t("healthRecords.riskAssessment.sections.doctorCustom") }}
      </h3>

      <div class="custom-risk-list">
        <div
          v-for="(risk, index) in customRisks"
          :key="index"
          class="custom-risk-item"
        >
          <div class="risk-row">
            <span class="risk-number">{{
              t("healthRecords.riskAssessment.riskLabels.riskTitle", {
                index: index + 1
              })
            }}</span>
            <el-input
              v-model="risk.title"
              :placeholder="
                t('healthRecords.riskAssessment.placeholders.enterRiskTitle')
              "
              class="risk-input"
            />
          </div>
          <div class="risk-row">
            <span class="risk-number">{{
              t("healthRecords.riskAssessment.riskLabels.riskContent", {
                index: index + 1
              })
            }}</span>
            <el-input
              v-model="risk.content"
              type="textarea"
              :rows="3"
              :placeholder="
                t('healthRecords.riskAssessment.placeholders.enterRiskContent')
              "
              class="risk-textarea"
            />
          </div>
          <el-link
            class="delete-btn"
            :icon="Delete"
            type="primary"
            @click="removeRisk(index)"
          />
        </div>
      </div>

      <el-button type="primary" class="add-btn" @click="addRisk">
        {{ t("healthRecords.riskAssessment.buttons.add") }}
      </el-button>
    </div>
  </div>
  <div class="drawer-footer">
    <el-button @click="handleCancel">{{
      t("healthRecords.riskAssessment.buttons.saveDraft")
    }}</el-button>
    <el-button type="primary" @click="handleSubmit">{{
      t("healthRecords.riskAssessment.buttons.submit")
    }}</el-button>
  </div>
</template>

<script lang="ts" setup>
import { reportApi } from "@/api/report-api";
import { RiskAssessmentItemVO } from "@/type/report";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";

// Props 和 Emits
interface Props {
  reportId: number;
  reportType?: number;
  requestSource?: string;
  isCreate?: boolean;
}

// 自定义风险评估数据
interface CustomRisk {
  title: string;
  content: string;
}

// const emit = defineEmits(["update-success"]);

const props = withDefaults(defineProps<Props>(), {
  reportId: 0,
  requestSource: "",
  isCreate: false
});

// 国际化
const { t } = useI18n();
// 数据状态
const loading = ref(false);
const aiRiskList = ref<RiskAssessmentItemVO[]>([]);
const customRisks = ref<CustomRisk[]>([]);

// 加载风险评估数据
const loadRiskAssessmentData = async () => {
  if (!props.reportId) {
    ElMessage.warning(
      t("healthRecords.riskAssessment.messages.missingReportId")
    );
    return;
  }

  loading.value = true;
  try {
    const params = {
      id: props.reportId,
      type: props.reportType
    };

    const response = await reportApi.queryRiskAssessmentList(params);

    if (response.code === 0 && response.data) {
      // 分离 AI 生成和自定义风险评估
      aiRiskList.value =
        response.data.riskAssessments?.filter(item => item.ai) || [];

      // 加载已有的自定义风险评估
      customRisks.value =
        response.data.riskAssessments?.filter(item => !item.ai) || [];
      if (customRisks.value.length === 0) {
        addRisk();
      }
    } else {
      ElMessage.error(
        response.message ||
          t("healthRecords.riskAssessment.messages.loadFailed")
      );
    }
  } catch (error) {
    console.error("加载风险评估数据失败:", error);
    ElMessage.error(t("healthRecords.riskAssessment.messages.loadFailed"));
  } finally {
    loading.value = false;
  }
};

// 添加风险项
const addRisk = () => {
  customRisks.value.push({
    title: "",
    content: ""
  });
};

// 删除风险项
const removeRisk = (index: number) => {
  ElMessageBox.confirm(
    t("healthRecords.riskAssessment.messages.deleteConfirm"),
    t("healthRecords.riskAssessment.messages.deleteTitle"),
    {
      confirmButtonText: t("healthRecords.riskAssessment.messages.confirmText"),
      cancelButtonText: t("healthRecords.riskAssessment.messages.cancelText"),
      type: "warning"
    }
  )
    .then(() => {
      customRisks.value.splice(index, 1);
    })
    .catch(() => {
      //
    });
};

// 保存草稿
const handleCancel = async () => {
  // 验证必填字段
  const hasEmptyFields = customRisks.value.some(
    risk => !risk.title.trim() || !risk.content.trim()
  );

  if (hasEmptyFields) {
    ElMessage.warning(t("healthRecords.riskAssessment.messages.fillComplete"));
    return;
  }

  try {
    const params = buildSubmitParams(1); // 1:保存草稿
    // 调用保存草稿接口
    const response = await reportApi.postRiskAssessmentSubmit(params);
    if (response.code == 0) {
      ElMessage.success(t("healthRecords.riskAssessment.messages.draftSaved"));
    } else {
      ElMessage.error(
        response.message ||
          t("healthRecords.riskAssessment.messages.submitFailed")
      );
    }
  } catch (error) {
    console.error("保存草稿失败:", error);
    ElMessage.error(t("healthRecords.riskAssessment.messages.saveDraftFailed"));
  }
};
// 引用 AI 风险评估
const quoteAiRisk = (aiRisk: RiskAssessmentItemVO) => {
  // 检查是否已经存在相同标题的风险评估
  const existingIndex = customRisks.value.findIndex(
    risk => risk.title === aiRisk.title
  );

  if (existingIndex !== -1) {
    ElMessage.warning(t("healthRecords.riskAssessment.messages.alreadyExists"));
    return;
  }

  // 添加到自定义风险评估列表
  customRisks.value.push({
    title: aiRisk.title,
    content: aiRisk.content,
    referenceId: aiRisk.referenceId
  });

  ElMessage.success(t("healthRecords.riskAssessment.messages.quoteSuccess"));
};
// 组装提交参数
const buildSubmitParams = (saveType: number) => {
  return {
    id: props.reportId,
    type: props.reportType,
    saveType: saveType, // 1:保存草稿, 2:提交
    requestSource: +props.requestSource,
    details: customRisks.value.map(risk => ({
      title: risk.title,
      content: risk.content,
      referenceId: risk.referenceId
    }))
  };
};
// 处理提交
const handleSubmit = async () => {
  // 验证数据
  const hasEmptyFields = customRisks.value.some(
    risk => !risk.title.trim() || !risk.content.trim()
  );
  if (hasEmptyFields) {
    ElMessage.warning(t("healthRecords.riskAssessment.messages.fillComplete"));
    return;
  }

  try {
    const params = buildSubmitParams(2); // 2:提交
    // 调用提交接口
    const response = await reportApi.postRiskAssessmentSubmit(params);
    if (response.code == 0) {
      ElMessage.success(
        t("healthRecords.riskAssessment.messages.submitSuccess")
      );
    } else {
      ElMessage.error(
        response.message ||
          t("healthRecords.riskAssessment.messages.submitFailed")
      );
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error(error.message);
  }
};
onMounted(() => {
  if (!props.isCreate) {
    loadRiskAssessmentData();
  } else {
    addRisk();
  }
});
</script>

<style lang="scss" scoped>
.risk-assessment {
  display: flex;
}
.risk-section {
  flex: 1;
  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-left: 8px;
    border-left: 3px solid #409eff;
  }
}

.risk-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 12px;

  .risk-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .risk-label {
      font-weight: 500;
      color: #606266;
    }
  }

  .risk-content {
    margin: 0;
    color: #909399;
    line-height: 1.5;
  }
}

.custom-risk-list {
  .custom-risk-item {
    margin-bottom: 20px;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background: #fff;
    position: relative;

    .risk-row {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;
      margin-right: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      .risk-number {
        min-width: 100px;
        padding-top: 8px;
        font-size: 14px;
        color: #606266;
        flex-shrink: 0;
      }

      .risk-input {
        flex: 1;
      }

      .risk-textarea {
        flex: 1;
      }
    }
    .delete-btn {
      position: absolute;
      top: 20px;
      right: 10px;
      font-size: 18px;
    }
  }
}

.drawer-footer {
  display: flex;
  justify-content: end;
  gap: 12px;
  padding: 16px 0;
}
</style>
